package com.token.model.dto;

import com.token.service.Consumer;

import java.util.Arrays;
import java.util.List;

/**
 * @auther: henriy
 * @Date: 2023/12/29
 */
public class ConsumerTest {

    private final Consumer<String> consumer;

    public ConsumerTest(Consumer<String> consumer) {
        this.consumer = consumer;
    }

    public void execute() {
        consumer.accept("Hello, Function Interface!");
    }

    public void getLength(String str) {
        System.out.println("getLength str==" + str);
        consumer.accept(str.length() + "");
    }

    public static void main(String[] args) {
        // 方式1：通过类构造器打印
        ConsumerTest example = new ConsumerTest(System.out::println);
        example.execute();

        ConsumerTest lengthConsumer = new ConsumerTest(System.out::println);
        lengthConsumer.getLength("http://www.baidu.com");

        Consumer<String> printConsumer = System.out::println;
        printConsumer.accept("http://www.baidu.com");

        Consumer<String> printLengthConsumer = s -> System.out.println(s.length());
        printLengthConsumer.accept("http://www.baidu.com");

        // andThen用法
        Consumer<String> length1Consumer = s -> System.out.println(s.length());
        Consumer<String> print1Consumer = length1Consumer.andThen(System.out::println);
        print1Consumer.accept("www");

        // 循环打印
        Consumer<String> print2Consumer = System.out::println;
        List<String> list = Arrays.asList("java", "node", "python");
        forEach(list, print2Consumer);
        // 打印长度
        forEach(list, s -> System.out.println(s.length()));
        forEach(list, System.out::println);
    }

    public static <T> void forEach(List<T> list, Consumer<T> consumer) {
        for (T t : list) {
            consumer.accept(t);
        }
    }

}
